package org.dong.Tool;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class MyWebServer {
    private ServerSocket serverSocket;

    public  MyWebServer(){

        try {
            //初始化一个客服务器，绑定监听端口
            ServerSocket serverSocket = new ServerSocket(1086);

            while(true){
                Socket socket = serverSocket.accept();
                new WebServerThread(socket).start();

            }


        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public void startServer(ServerSocket serverSocket){
        try {

            while(true){

                Socket socket  = serverSocket.accept();
                //创建输出流
                OutputStream os = socket.getOutputStream();
                //创建输入流
                InputStream is = socket.getInputStream();

                while(true) {

                    byte buf[] = new byte[1024*1024];

//                    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));

                    int let  = is.read(buf);
                    if(let == -1){
                        socket.close();
                        break;
                    }
                    String Msg = new String(buf,0,let,"utf-8");
                    String[] dataMsg = Msg.split("\r\n");
                    String[] infoMsg = dataMsg[0].split(" ");
                    //解析HTTP协议
                    //获取用户请求的资源路径

                    File file = new File("static" + infoMsg[1]);

                    if(!file.exists()){
                        socket.close();
                        break;
                    }
                    //获取mimeType
                    String path = file.getPath();
                    String mimeType = Data.getMIMEType(path);

                    StringBuilder sb = new StringBuilder();

                    sb.append("HTTP/1.1 200 OK\r\n");
                    sb.append("Content-type:" + mimeType + "\r\n");
                    sb.append("Content-Length:" + file.length() + "\r\n");
                    sb.append("\r\n");
                    os.write(sb.toString().getBytes(StandardCharsets.UTF_8));

                    //创建输出流
                    FileInputStream fis = new FileInputStream(file);
                    //创建字节组
                    byte[] bs = new byte[fis.available()];


                    fis.read(bs);

                    os.write(bs);

                    os.flush();

                    socket.close();
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }




 }